<template>
  <!-- 饼状图 -->
  <div class="roseStatisticsOptionTwoChart">
    <div
      :id="`roseStatisticsOptionTwoChart${getId}`"
      style="width: 100%; height: 100%"
    />
  </div>
</template>
 
<script>
/**
 * props接收到的optionObj
 * optionObj: {
 *  @params isNewline label是否换行
 *  @params isPerNum 显示数值为占比还是数量
 *  @params isLegendBox legend是否显示
 *  @params valuePadding value的间距
 *  @params numPadding  值的间距
 *  @params fontSize 字体大小
 *  @params isValueShow 是否显示数值
 *  （*解决少数界面需要的简单的legend样式不统一的情况）
 *  @params icon 图例形状
 *  @params padding 图例padding
 *  @params itemGap 图例距离
 *  @params width 图例宽度
 * ---
 *  @params center 位置
 *  @params radius 环占比
 *  @params length  引导线长度1
 *  @params length2 引导线长度2
 *  @params right legend右侧距离
 *  @params top legend顶部距离
 * }
 */
const echarts = require("echarts");
export default {
  name: "PieChart",
  props: {
    chartData: {
      type: Array,
    },
    getId: {
      type: String,
    },
    optionObj: {
      type: Object,
      default: () => {
        return {
          titleShow: false,
          isNewline: true,
          isPerNum: true,
          isLegendBox: true,
          y: "center",
          valuePadding: [0, 0, 0, 0],
          numPadding: [0, 0, 0, 0],
          fontSize: [14, 14],
          isValueShow: true,
          icon: "circle",
          padding: [30, 30, 30, 30],
          itemGap: 20,
          width: "",
          colorList: [
            "#4CBAFF",
            "#41FDFE",
            "#A040FE",
            "#E1CE10",
            "#F35AF7",
            "#FD706E",
            "rgba(156, 43, 182, 1)",
          ],
          center: ["50%", "45%"],
          radius: [30, 55],
          length: 2,
          length2: 10,
          right: "auto",
          inside: false,
          legendValue: false,
          itemWidth: 14,
          itemHeight: 14,
          richWidth: 100,
          percentage: false,
          numWidth: 70,
          titleColor: false,
        };
      },
    },
  },
  data() {
    return {
      timeInterval: null,
      chart: null,
      option: {},
      color: [
        "#4CBAFF",
        "#41FDFE",
        "#E1CE10",
        "#A040FE",
        "#F35AF7",
        "#FD706E",
        "rgba(156, 43, 182, 1)",
      ],
    };
  },
  watch: {
    chartData: {
      handler() {
        // this.option.series[0].data = val

        // this.chart.setOption(this.option)
        this.draw();
      },
      deep: true,
    },
  },
  mounted() {
    this.draw();
    this.$nextTick(() => {
      this.chart.resize();
      const dom1 = document.getElementById(
        `roseStatisticsOptionTwoChart${this.getId}`
      );
      const myChart = echarts.init(dom1);
      myChart.on("click", (param) => {
        // 这里使用箭头函数代替function，this指向VueComponent
        // let index
        // 当前扇区的dataIndex
        // index = param.dataIndex
        // 自己的操作，这里是点击跳转路由，并携带参数
        console.log(param);
        this.$emit("getbing", param);
      });
    });
  },
  destroyed() {
    window.removeEventListener("resize", this.onResize);
    window.onresize = null;
    this.stopInterval();
  },
  methods: {
    draw() {
      // 基于准备好的dom，初始化echarts实例
      let legendData = this.chartData;
      let flag = this.optionObj.legendValue;
      this.chart = echarts.init(
        document.getElementById(`roseStatisticsOptionTwoChart${this.getId}`)
      );
      let top = parseInt(this.optionObj.center[1]) - 5;
      let total = 0;
      this.chartData.forEach((v) => {
        total += v.value;
      });

      this.option = {
        color: this.optionObj.colorList,
        title: {
          show: this.optionObj.inside || false,
          text: total,
          // subtext: '总平均值(分)',
          // offsetCenter: this.optionObj.center,
          // y: this.optionObj.center[1],
          left: "center",
          top: top,
          textStyle: {
            fontSize: 30,
            fontFamily: "Orbitron",

            fontWeight: "bold",
            color: "#fff",
            shadowBlur: 5, // 图形阴影的模糊大小
            shadowColor: "rgba(0,255,226,0.5)", // 阴影颜色
          },
        },
        grid: {
          top: "50%",
          left: "0%",
          right: "0%",
          bottom: "0%",
        },
        legend: {
          orient: "vertical",
          // type: 'scroll',
          // top: this.optionObj.top || 'bottom',
          right: this.optionObj.right || "auto",
          icon: this.optionObj.icon,
          itemWidth: this.optionObj.itemWidth || 14,
          itemHeight: this.optionObj.itemHeight || 14,
          y: "center",
          show: this.optionObj.isLegendBox,
          padding: this.optionObj.padding,
          itemGap: this.optionObj.itemGap,
          width: this.optionObj.width,
          selectedMode: false, // 屏蔽图例
          textStyle: {
            fontSize: 9,
            color: "#666666",
            padding: [0, 0, 0, 0],
            rich: {
              a0: {
                width: this.optionObj.richWidth,
                fontSize: this.optionObj.fontSize[0],
                align: "left",
              },
              a1: {
                width: this.optionObj.richWidth,
                fontSize: this.optionObj.fontSize[0],
                align: "left",
              },
              a2: {
                width: this.optionObj.richWidth,
                fontSize: this.optionObj.fontSize[0],
                align: "left",
              },
              a3: {
                width: this.optionObj.richWidth,
                fontSize: this.optionObj.fontSize[0],
                align: "left",
              },
              a4: {
                width: this.optionObj.richWidth,
                fontSize: this.optionObj.fontSize[0],
                align: "left",
              },
              a5: {
                width: this.optionObj.richWidth2 || this.optionObj.richWidth,
                fontSize: this.optionObj.fontSize[0],
                align: "left",
              },
              a6: {
                width: this.optionObj.richWidth2 || this.optionObj.richWidth,
                fontSize: this.optionObj.fontSize[0],
                align: "left",
              },
              a7: {
                width: this.optionObj.richWidth2 || this.optionObj.richWidth,
                fontSize: this.optionObj.fontSize[0],
                align: "left",
              },
              a8: {
                width: this.optionObj.richWidth2 || this.optionObj.richWidth,
                fontSize: this.optionObj.fontSize[0],
                align: "left",
              },
              a9: {
                width: this.optionObj.richWidth2 || this.optionObj.richWidth,
                fontSize: this.optionObj.fontSize[0],
                align: "left",
              },
              a10: {
                width: this.optionObj.richWidth2 || this.optionObj.richWidth,
                fontSize: this.optionObj.fontSize[0],
                align: "left",
              },
              b0: {
                width: this.optionObj.numWidth,
                fontSize: this.optionObj.fontSize[1],
                align: "right",
                fontFamily: "Orbitron",
                color: this.optionObj.titleColor || this.optionObj.colorList[0],
              },
              b1: {
                width: this.optionObj.numWidth,
                fontSize: this.optionObj.fontSize[1],
                align: "right",
                fontFamily: "Orbitron",
                color: this.optionObj.titleColor || this.optionObj.colorList[1],
              },
              b2: {
                width: this.optionObj.numWidth,
                fontSize: this.optionObj.fontSize[1],
                align: "right",
                fontFamily: "Orbitron",
                color: this.optionObj.titleColor || this.optionObj.colorList[2],
              },
              b3: {
                width: this.optionObj.numWidth,
                fontSize: this.optionObj.fontSize[1],
                align: "right",
                fontFamily: "Orbitron",
                color: this.optionObj.titleColor || this.optionObj.colorList[3],
              },
              b4: {
                width: this.optionObj.numWidth,
                fontSize: this.optionObj.fontSize[1],
                align: "right",
                fontFamily: "Orbitron",
                color: this.optionObj.titleColor || this.optionObj.colorList[4],
              },
              b5: {
                width: this.optionObj.numWidth,
                fontSize: this.optionObj.fontSize[1],
                align: "right",
                fontFamily: "Orbitron",
                color: this.optionObj.titleColor || this.optionObj.colorList[5],
              },
              b6: {
                width: this.optionObj.numWidth,
                fontSize: this.optionObj.fontSize[1],
                align: "right",
                fontFamily: "Orbitron",
                color: this.optionObj.titleColor || this.optionObj.colorList[6],
              },
              b7: {
                width: this.optionObj.numWidth,
                fontSize: this.optionObj.fontSize[1],
                align: "right",
                fontFamily: "Orbitron",
                color: this.optionObj.titleColor || this.optionObj.colorList[6],
              },
              b8: {
                width: this.optionObj.numWidth,
                fontSize: this.optionObj.fontSize[1],
                align: "right",
                fontFamily: "Orbitron",
                color: this.optionObj.titleColor || this.optionObj.colorList[7],
              },
              b9: {
                width: this.optionObj.numWidth,
                fontSize: this.optionObj.fontSize[1],
                align: "right",
                fontFamily: "Orbitron",
                color: this.optionObj.titleColor || this.optionObj.colorList[8],
              },
              b10: {
                width: this.optionObj.numWidth,
                fontSize: this.optionObj.fontSize[1],
                align: "right",
                fontFamily: "Orbitron",
                color: this.optionObj.titleColor || this.optionObj.colorList[9],
              },
              b11: {
                width: this.optionObj.numWidth,
                fontSize: this.optionObj.fontSize[1],
                align: "right",
                fontFamily: "Orbitron",
                color:
                  this.optionObj.titleColor || this.optionObj.colorList[10],
              },
            },
          },
          formatter: (param) => {
            let index = 0;
            legendData.forEach((v, i) => {
              if (v.name === param) {
                index = i;
              }
            });
            let item = legendData[index];
            // let bfs = fomatFloat(item.value * 100, 2) + '%'
            total;

            let strs = item.name;
            // eslint-disable-next-line no-unused-vars
            let str = null;

            // eslint-disable-next-line space-in-parens
            for (var i = 0, s; (s = strs[i++]); ) {
              // 遍历字符串数组
              str += s;
              if (!(i % 15)) str += "\n"; // 按需要求余
            }
            return flag
              ? `{a${index}|${
                  param.length > 17 ? param.substr(0, 17) + "..." : param
                }}   {b${index}|${total ? item.value : ""}}        `
              : `{a${index}|${
                  param.length > 17 ? param.substr(0, 17) : param
                }}   {b${index}|${item.value}}        `;
          },
        },
        series: [
          {
            color: this.optionObj.colorList,
            name: "Nightingale Chart",
            type: "pie",
            radius: this.optionObj.radius || [30, 65],
            center: this.optionObj.center || ["50%", "50%"],
            // roseType: 'area',
            startAngle: 270,
            label: {
              normal: {
                show: false,
                position: "center",
                // formatter: this.optionObj.percentage ? '{value|{d}%}\n{label|{b}}' : '{value|{c}}\n{label|{b}}',
                formatter: (val) => {
                  var strs = val.name; // 字符串数组
                  var str = "";
                  // eslint-disable-next-line space-in-parens
                  for (var i = 0, s; (s = strs[i++]); ) {
                    // 遍历字符串数组
                    str += s;
                    if (!(i % 6)) str += "\n"; // 按需要求余
                  }
                  return this.optionObj.percentage
                    ? `{value|${str}}\n{label|${val.percent}%}`
                    : `{value|${val.value}}\n{label|${str}}`;
                },
                rich: {
                  value: {
                    padding: 5,
                    align: "center",
                    verticalAlign: "middle",
                    fontSize: 20,
                    fontFamily: "Orbitron",
                    color: "#666666",
                  },
                  label: {
                    align: "center",
                    verticalAlign: "middle",
                    fontWeight: "600",
                    fontSize: 25,
                    color: "#666666",
                  },
                },
              },

              emphasis: {
                show: true, // 中间文字内容是否显示
                textStyle: {
                  fontSize: "12",
                },
              },
            },

            data: this.chartData,
          },
        ],
      };
      if (this.optionObj.inside) {
        this.option.series[1] = {
          radius: ["30%", "35%"],
          center: this.optionObj.center || ["50%", "50%"],
          type: "pie",
          itemStyle: {
            normal: {
              color: "#35415B",
              label: {
                show: false,
              },
              labelLine: {
                show: false,
              },
            },
          },
          data: [
            {
              value: 1,
            },
          ],
        };
      }
      this.chart.setOption(this.option);
      window.addEventListener("resize", this.onResize);
      // 启动定时器方法
      // 启动定时器方法
      this.openInterVal(this.option);
      this.chart.setOption(this.option);
      // 图形hover事件
      this.chart.on("mouseover", (params) => {
        this.stopInterval();
        const dataLen = this.option.series[0].data.length;
        for (let i = 0; i < dataLen; i++) {
          // 取消之前高亮的图形
          this.chart.dispatchAction({
            type: "downplay",
            seriesIndex: 0,
            dataIndex: i,
          });
        }
        this.chart.dispatchAction({
          type: "highlight",
          seriesIndex: 0,
          dataIndex: params.dataIndex,
        });
        // this.chart.setOption(this.option)
      });
      this.chart.on("mouseout", () => {
        const dataLen = this.option.series[0].data.length;
        for (let i = 0; i < dataLen; i++) {
          // 取消之前高亮的图形
          this.chart.dispatchAction({
            type: "downplay",
            seriesIndex: 0,
            dataIndex: i,
          });
        }
        this.openInterVal(this.option);
      });
      window.addEventListener("resize", this.onResize);
    },
    stopInterval() {
      if (this.timeInterval) {
        clearInterval(this.timeInterval);
      }
      this.timeInterval = null;
    },
    openInterVal(option) {
      this.stopInterval(); //* 暂定改为移入停止，移出从0开始
      // 自动轮播
      var currentIndex = -1;
      var dataLen = option.series[0].data.length;
      this.timeInterval = setInterval(() => {
        // 取消之前高亮的图形
        this.chart.dispatchAction({
          type: "downplay",
          seriesIndex: 0,
          dataIndex: currentIndex,
        });
        currentIndex = (currentIndex + 1) % dataLen;
        // 高亮当前图形
        this.chart.dispatchAction({
          type: "highlight",
          seriesIndex: 0,
          dataIndex: currentIndex,
        });
        // 显示 tooltip
        // this.chart.dispatchAction({
        //   type: 'showTip',
        //   seriesIndex: 0,
        //   dataIndex: currentIndex,
        // })
      }, 3000);
    },
    // 切换数据后默认从第一项开始轮询
    initPolling() {
      const dataLen = this.option.series[0].data.length;
      for (let i = 0; i < dataLen; i++) {
        // 取消之前高亮的图形
        this.chart.dispatchAction({
          type: "downplay",
          seriesIndex: 0,
          dataIndex: i,
        });
      }
    },
    onResize() {
      this.chart.resize();
    },
  },
};
</script>

  <style lang="scss" scoped>
.roseStatisticsOptionTwoChart {
  width: 100%;
  height: 100%;
}
</style>

